package com.jacob.androidframe.database;

import java.util.List;

import com.jacob.androidframe.controls.ApplicationExtend;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 数据库开闭帮助类，用来创建数据库、管理数据库版本。
 * 本类使用单例模式。
 * 
 * @author 王超
 */
public class SQLiteOpenAssistant extends SQLiteOpenHelper
{
	// 私有化构造方法
	private SQLiteOpenAssistant()
	{
		super(ApplicationExtend.getInstance(), DatabaseConfig.getDatabaseName(), null, DatabaseConfig.getVersion());
	}

	// 加载SQLiteOpenAssistant类的时候会加载SQLiteOpenAssistantHolder类，但不会初始化INSTANCE。
	private static class SQLiteOpenAssistantHolder
	{
		private static SQLiteOpenAssistant	INSTANCE	= new SQLiteOpenAssistant();
	}

	// 返回单例对象
	public static SQLiteOpenAssistant getInstance()
	{
		return SQLiteOpenAssistantHolder.INSTANCE;
	}

	@Override
	public void onCreate(SQLiteDatabase pSqLiteDatabase)
	{
		List<String> _SqlList = DatabaseConfig.getCreatDatabaseSql();

		for (String _Sql : _SqlList)
		{
			System.out.println("执行SQL:" + _Sql);
			pSqLiteDatabase.execSQL(_Sql);
		}

	}

	@Override
	public void onUpgrade(SQLiteDatabase pSqLiteDatabase, int pOldVersion, int pNewVersion)
	{
		List<String> _SqlList = DatabaseConfig.getUpgrateDatabaseSql(pOldVersion, pNewVersion);

		for (String _Sql : _SqlList)
		{
			System.out.println("执行SQL:" + _Sql);
			pSqLiteDatabase.execSQL(_Sql);
		}
	}

	@Override
	public void onOpen(SQLiteDatabase pSqLiteDatabase)
	{
		// 打开数据库时，强制开启外键支持。以便进行级联删除、更新。
		if (!pSqLiteDatabase.isReadOnly()) {
			pSqLiteDatabase.execSQL("PRAGMA foreign_keys=ON;");
		}
	}

}
